import {useSelector,useDispatch} from 'react-redux'
import {useEffect} from 'react'
import {getShopcartDataAsync,changeNumAsync} from '@/store/async/shopcartAsync'
export default ()=>{
    const list=useSelector(state=>{
        return state.shopcartKey.list
    })
    const dispatch=useDispatch()
    useEffect(()=>{
        //如果你调用的异步方法不需要传递参数，直接异步方法的名称
        dispatch(getShopcartDataAsync)
    },[])
    const changeNum=(arg)=>{
        dispatch(changeNumAsync(arg))
    }



    return (<>
        <h1>Redux-thunk版的购物车</h1>
        <table>
            <thead>
                <tr>
                    <td>商品名称</td>
                    <td>商品价格</td>
                    <td>商品数量</td>
                    <td>商品小计</td>
                </tr>
            </thead>
            <tbody>
                {
                    list.length>0&&list.map(item=><tr key={item._id}>
                        <td>{item.name}</td>
                        <td>{item.price}</td>
                        <td>
                            <button onClick={()=>{
                                 changeNum({_id:item._id,n:-1})
                            }}>-</button>
                            <span>{item.num}</span>
                            <button onClick={()=>{
                                changeNum({_id:item._id,n:1})
                            }}>+</button>
                        </td>
                        <td>{item.price*item.num}</td>
                    </tr>)
                }
            </tbody>
        </table>
    </>)
}